package jnpf.zcasset.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.util.IdPO;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.MsgCode;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetDisposeDetailsEntity;
import jnpf.zcasset.entity.ZcAssetDisposeEntity;
import jnpf.zcasset.entity.ZcAssetDisposeProcessEntity;
import jnpf.zcasset.entity.ZcAssetInfoEntity;
import jnpf.zcasset.model.zcassetdispose.*;
import jnpf.zcasset.model.zcassetdisposeprocess.ZcAssetDisposeProcessCompleteForm;
import jnpf.zcasset.model.zcassetdisposeprocess.ZcAssetDisposeProcessForm;
import jnpf.zcasset.service.ZcAssetDisposeDetailsService;
import jnpf.zcasset.service.ZcAssetDisposeService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资产处置
 *
 * @版本： V3.2.0
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @
 */
@Slf4j
@RestController
@Api(tags = "资产处置", value = "zc")
@RequestMapping("/api/zc/ZcAssetDispose")
public class ZcAssetDisposeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ZcAssetDisposeService zcAssetDisposeService;

    @Autowired
    private ZcAssetDisposeDetailsService zcAssetDisposeDetailsService;

    /**
     * 列表
     *
     * @param zcAssetDisposePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcAssetDisposePagination zcAssetDisposePagination) throws IOException {
        List<ZcAssetDisposeEntity> list = zcAssetDisposeService.getList(zcAssetDisposePagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcAssetDisposeListVO> listVO = JsonUtil.getJsonToList(list, ZcAssetDisposeListVO.class);
        for (ZcAssetDisposeListVO zcAssetDisposeVO : listVO) {
            zcAssetDisposeVO.setDisposalType_name(generaterSwapUtil.getDicName(zcAssetDisposeVO.getDisposalType(), "610927980662751941"));
            zcAssetDisposeVO.setDisposalUnit_name(generaterSwapUtil.getDicName(zcAssetDisposeVO.getDisposalUnit(), "610824142995849541"));

//            //子表数据转换
//            List<ZcAssetDisposeDetailsEntity> zcAssetDisposeDetailsList = zcAssetDisposeService.getZcAssetDisposeDetailsList(zcAssetDisposeVO.getId(), zcAssetDisposePagination);
//            List<ZcAssetDisposeDetailsModel> zcAssetDisposeDetailsModelList = JsonUtil.getJsonToList(zcAssetDisposeDetailsList, ZcAssetDisposeDetailsModel.class);
//            for (ZcAssetDisposeDetailsModel zcAssetDisposeDetailsModel : zcAssetDisposeDetailsModelList) {
//            }
//            zcAssetDisposeVO.setZcAssetDisposeDetailsList(zcAssetDisposeDetailsModelList);
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcAssetDisposePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zcAssetDisposeForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcAssetDisposeForm zcAssetDisposeForm) throws DataException {
        boolean b = zcAssetDisposeService.checkForm(zcAssetDisposeForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcAssetDisposeEntity entity = JsonUtil.getJsonToBean(zcAssetDisposeForm, ZcAssetDisposeEntity.class);
        entity.setId(mainId);
        entity.setCreatorUserId(userProvider.get().getUserId());
        zcAssetDisposeService.save(entity);
        if (zcAssetDisposeForm.getZcassetdisposedetailsList() != null) {
            List<ZcAssetDisposeDetailsEntity> ZcAssetDisposeDetailsList = JsonUtil.getJsonToList(zcAssetDisposeForm.getZcassetdisposedetailsList(), ZcAssetDisposeDetailsEntity.class);
            for (ZcAssetDisposeDetailsEntity entitys : ZcAssetDisposeDetailsList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setAssetDisposeId(entity.getId());
                entitys.setCreatorUserId(userProvider.get().getUserId());
                zcAssetDisposeDetailsService.save(entitys);
            }
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 模板下载
     *
     * @return
     */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = DownloadVO.builder().build();
        try {
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=", userInfo.getId() + "#" + "职员信息.xlsx" + "#" + "Temporary"));
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
        }
        return ActionResult.success(vo);
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ZcAssetDisposePagination zcAssetDisposePagination) throws IOException {
        if (StringUtil.isEmpty(zcAssetDisposePagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<ZcAssetDisposeEntity> list = zcAssetDisposeService.getTypeList(zcAssetDisposePagination, zcAssetDisposePagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcAssetDisposeListVO> listVO = JsonUtil.getJsonToList(list, ZcAssetDisposeListVO.class);
        for (ZcAssetDisposeListVO zcAssetDisposeVO : listVO) {
            zcAssetDisposeVO.setDisposalType_name(generaterSwapUtil.getDicName(zcAssetDisposeVO.getDisposalType(), "610927980662751941"));
            zcAssetDisposeVO.setDisposalUnit_name(generaterSwapUtil.getDicName(zcAssetDisposeVO.getDisposalUnit(), "610824142995849541"));

//            //子表数据转换
//            List<ZcAssetDisposeDetailsEntity> zcAssetDisposeDetailsList = zcAssetDisposeService.getZcAssetDisposeDetailsList(zcAssetDisposeVO.getId(), zcAssetDisposePagination);
//            List<ZcAssetDisposeDetailsModel> zcAssetDisposeDetailsModelList = JsonUtil.getJsonToList(zcAssetDisposeDetailsList, ZcAssetDisposeDetailsModel.class);
//            for (ZcAssetDisposeDetailsModel zcAssetDisposeDetailsModel : zcAssetDisposeDetailsModelList) {
//            }
//            zcAssetDisposeVO.setZcAssetDisposeDetailsList(zcAssetDisposeDetailsModelList);
        }

        //转换为map输出
        List<Map<String, Object>> mapList = JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO, "yyyy-MM-dd HH:mm:ss"));
        mapList.stream().forEach(map -> {
            Map<String, Object> map2 = new HashMap<>();
            map.putAll(map2);
            List<Map<String, Object>> tableField109Map = JsonUtil.getJsonToListMap(String.valueOf(map.get("tableField109")));
//            for (Map<String, Object> mp : tableField109Map) {
//            }
            map.put("tableField109", tableField109Map);
        });
        String[] keys = !StringUtil.isEmpty(zcAssetDisposePagination.getSelectKey()) ? zcAssetDisposePagination.getSelectKey().split(",") : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), mapList, keys, userInfo);
        return ActionResult.success(vo);
    }

    //导出表格
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            ExcelExportEntity tableField109ExcelEntity = new ExcelExportEntity("设计子表", "tableField109");
            List<ExcelExportEntity> tableField109List = new ArrayList<>();
            for (String key : keys) {
                switch (key) {
                    case "disposalTitle":
                        entitys.add(new ExcelExportEntity("处置标题", "disposalTitle"));
                        break;
                    case "disposalType":
                        entitys.add(new ExcelExportEntity("处置方式", "disposalType_name"));
                        break;
                    case "startDate":
                        entitys.add(new ExcelExportEntity("开始日期", "startDate"));
                        break;
                    case "disposalAgent":
                        entitys.add(new ExcelExportEntity("经办人", "disposalAgent"));
                        break;
                    case "disposalUnit":
                        entitys.add(new ExcelExportEntity("处置单位", "disposalUnit_name"));
                        break;
                    case "disposalSpecification":
                        entitys.add(new ExcelExportEntity("处置说明", "disposalSpecification"));
                        break;
                    case "tableField109-assetId":
                        tableField109List.add(new ExcelExportEntity("资产信息", "assetId"));
                        break;
//                    case "tableField109-creatoruserid":
//                        tableField109List.add(new ExcelExportEntity("创建人", "creatoruserid"));
//                        break;
                    default:
                        break;

                }
            }
            List<String> keylist = new ArrayList<>();
            for (String key : keys) {
                keylist.add(key);
            }
            if (tableField109List.size() > 0) {
                String tableField109 = keylist.stream().filter(k -> k.startsWith("tableField109")).findFirst().orElse("");
                List<String> tableField109st = keylist.stream().filter(k -> k.startsWith("tableField109")).collect(Collectors.toList());
                tableField109ExcelEntity.setList(tableField109List);
                entitys.add(keylist.indexOf(tableField109), tableField109ExcelEntity);
                keylist.removeAll(tableField109st);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";

            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }

    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcAssetDisposeInfoVO> info(@PathVariable("id") String id) {
        ZcAssetDisposeEntity entity = zcAssetDisposeService.getInfo(id);
        ZcAssetDisposeInfoVO vo = JsonUtil.getJsonToBean(entity, ZcAssetDisposeInfoVO.class);

        //子表
//        List<ZcAssetDisposeDetailsEntity> ZcAssetDisposeDetailsList = zcAssetDisposeService.getZcAssetDisposeDetailsList(id);
//        for (ZcAssetDisposeDetailsEntity zcassetdisposedetailsEntity : ZcAssetDisposeDetailsList) {
//        }
//        vo.setZcAssetDisposeDetailsList(JsonUtil.getJsonToList(ZcAssetDisposeDetailsList, ZcAssetDisposeDetailsModel.class));

        //子表数据转换
        List<ZcAssetDisposeDetailsModel> zcAssetDisposeDetailsModelList = zcAssetDisposeService.getZcAssetDisposeDetailsModelList(entity.getId());
//        List<ZcAssetDisposeDetailsEntity> zcAssetDisposeDetailsList = zcAssetDisposeService.getZcAssetDisposeDetailsList(id);
//        List<ZcAssetDisposeDetailsModel> zcAssetDisposeDetailsModelList = JsonUtil.getJsonToList(zcAssetDisposeDetailsList, ZcAssetDisposeDetailsModel.class);
//        for (ZcAssetDisposeDetailsModel zcAssetDisposeDetailsModel : zcAssetDisposeDetailsModelList) {
//        }
        vo.setZcAssetDisposeDetailsList(zcAssetDisposeDetailsModelList);
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcAssetDisposeInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcAssetDisposeEntity entity = zcAssetDisposeService.getInfo(id);
        ZcAssetDisposeInfoVO vo = JsonUtil.getJsonToBean(entity, ZcAssetDisposeInfoVO.class);

        //子表数据转换
        List<ZcAssetDisposeDetailsModel> zcAssetDisposeDetailsModelList = zcAssetDisposeService.getZcAssetDisposeDetailsModelList(entity.getId());
//        List<ZcAssetDisposeDetailsEntity> zcAssetDisposeDetailsList = zcAssetDisposeService.getZcAssetDisposeDetailsList(id);
//        List<ZcAssetDisposeDetailsModel> zcAssetDisposeDetailsModelList = JsonUtil.getJsonToList(zcAssetDisposeDetailsList, ZcAssetDisposeDetailsModel.class);
//        for (ZcAssetDisposeDetailsModel zcAssetDisposeDetailsModel : zcAssetDisposeDetailsModelList) {
//        }
        vo.setZcAssetDisposeDetailsList(zcAssetDisposeDetailsModelList);

        //附表数据转换

//添加到详情表单对象中
        vo.setDisposalTitle(vo.getDisposalTitle());

        vo.setDisposalType(generaterSwapUtil.getDicName(vo.getDisposalType(), "610927980662751941"));

        vo.setStartDate(vo.getStartDate());

        vo.setDisposalAgent(vo.getDisposalAgent());

        vo.setDisposalUnit(generaterSwapUtil.getDicName(vo.getDisposalUnit(), "610824142995849541"));

        vo.setDisposalSpecification(vo.getDisposalSpecification());
        return ActionResult.success(vo);
    }

    /**
     * 更新
     *
     * @param id
     * @param zcAssetDisposeForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcAssetDisposeForm zcAssetDisposeForm) throws DataException {
        boolean b = zcAssetDisposeService.checkForm(zcAssetDisposeForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo = userProvider.get();
        ZcAssetDisposeEntity entity = zcAssetDisposeService.getInfo(id);
        if (entity != null) {
            ZcAssetDisposeEntity subentity = JsonUtil.getJsonToBean(zcAssetDisposeForm, ZcAssetDisposeEntity.class);
            subentity.setLastModifyUserId(userProvider.get().getUserId());
            boolean b1 = zcAssetDisposeService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<ZcAssetDisposeDetailsEntity> ZcAssetDisposeDetailsqueryWrapper = new QueryWrapper<>();
            ZcAssetDisposeDetailsqueryWrapper.lambda().eq(ZcAssetDisposeDetailsEntity::getAssetDisposeId, entity.getId());
            zcAssetDisposeDetailsService.remove(ZcAssetDisposeDetailsqueryWrapper);
            if (zcAssetDisposeForm.getZcassetdisposedetailsList() != null) {
                List<ZcAssetDisposeDetailsEntity> ZcAssetDisposeDetailsList = JsonUtil.getJsonToList(zcAssetDisposeForm.getZcassetdisposedetailsList(), ZcAssetDisposeDetailsEntity.class);
                for (ZcAssetDisposeDetailsEntity entitys : ZcAssetDisposeDetailsList) {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setAssetDisposeId(entity.getId());
                    entitys.setLastModifyUserId(userProvider.get().getUserId());
                    zcAssetDisposeDetailsService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcAssetDisposeEntity entity = zcAssetDisposeService.getInfo(id);
        if (entity != null) {
            zcAssetDisposeService.delete(entity);
            QueryWrapper<ZcAssetDisposeDetailsEntity> queryWrapperZcAssetDisposeDetails = new QueryWrapper<>();
            queryWrapperZcAssetDisposeDetails.lambda().eq(ZcAssetDisposeDetailsEntity::getAssetDisposeId, entity.getId());

            zcAssetDisposeDetailsService.remove(queryWrapperZcAssetDisposeDetails);

        }
        return ActionResult.success("删除成功");
    }


    /**
     * 查询资产列表
     *
     * @param po
     * @return
     */
    @ApiOperation("查询资产列表")
    @PostMapping("/queryAssetList")
    public ActionResult queryAssetList(@RequestBody IdPO po) throws IOException {
        List<ZcAssetInfoEntity> list = zcAssetDisposeService.queryAssetListById(po.getId());
        return ActionResult.success(list);
    }


    /**
     * 添加处置过程
     *
     * @param form
     * @return
     */
    @ApiOperation("添加处置过程")
    @PostMapping("/addDisposeProcess")
    public ActionResult addDisposeProcess(@RequestBody @Valid ZcAssetDisposeProcessForm form) throws IOException {
        boolean bool = zcAssetDisposeService.addDisposeProcess(form);
        return bool ? ActionResult.success(MsgCode.SU002.get()) : ActionResult.fail(MsgCode.FA101.get());
    }

    /**
     * 添加处置过程
     *
     * @param form
     * @return
     */
    @ApiOperation("添加处置过程")
    @PostMapping("/addDisposeProcessComplete")
    public ActionResult addDisposeProcessComplete(@RequestBody @Valid ZcAssetDisposeProcessCompleteForm form) throws IOException {
        boolean bool = zcAssetDisposeService.addDisposeProcessComplete(form);
        return bool ? ActionResult.success(MsgCode.SU002.get()) : ActionResult.fail(MsgCode.FA101.get());
    }


    /**
     * 查询处置过程列表
     *
     * @param po
     * @return
     */
    @ApiOperation("查询处置过程列表")
    @PostMapping("/queryDisposeProcessList")
    public ActionResult queryDisposeProcessList(@RequestBody IdPO po) throws IOException {
        List<ZcAssetDisposeProcessEntity> list = zcAssetDisposeService.queryDisposeProcessList(po.getId());
        return ActionResult.success(list);
    }
}
